// 创建用户相关的小仓库
import { defineStore } from 'pinia'
// 引入接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
// 引入数据类型
import type { loginFormData, loginResponseData, userInfoReponseData } from '@/api/user/type'

import type { UserState } from './types/type'
// 引入操作本地存储的工具方法
import { REMOVE_TOKEN } from '@/utils/token'
// 引入路由（常量路由）
import { constantRoute } from '@/router/routes'
// 创建用户小仓库
let useUserStore = defineStore('User', {
  // 小仓库存储数据地方
  state: (): UserState => {
    return {
      token: localStorage.getItem("TOKEN"),
      menuRoutes: constantRoute,  //路由
      username: '',
      avatar: '',
    }
  },
  // 异步、逻辑
  actions: {
    // 用户登录
    async userLogin(data: loginFormData) {
      let result: loginResponseData = await reqLogin(data)

      if (result.code == 200) {
        this.token = (result.data as string)
        localStorage.setItem("TOKEN", (result.data as string))
        // 能保证当前async函数返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    // 获取用户信息
    async userInfo() {
      let result: userInfoReponseData = await reqUserInfo()

      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    // 退出登录
    async userLogout() {
      let result: any = await reqLogout()
      if (result.code == 200) {
        this.token = ''
        this.username = ''
        this.avatar = ''
        // localStorage.removeItem('TOKEN')
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }

    }
  },
  getters: {}
})

// 对外暴露获取小仓库方法
export default useUserStore